<template>
  <n-modal v-model:show="visible">
    <n-card
      :style="{ width: schema.dialogWidth || '500px' }"
      :title="dialogTitle || schema.title"
      :bordered="false"
      role="dialog"
      aria-modal="true"
      closable
      @close="close"
    >
      <n-scrollbar :style="{ maxHeight: schema.dialogHeight || '500px' }">
        <formBuilder ref="formBuilderRef" :schema="schema"></formBuilder>
      </n-scrollbar>

      <template #footer>
        <n-space justify="end">
          <n-button @click="handleSubmit" type="success" secondary strong>{{
            $t("submit")
          }}</n-button>
        </n-space>
      </template>
    </n-card>
  </n-modal>
</template>

<script lang="ts" setup>
import { ref, PropType } from "vue";
import { IForm } from "@/components/form-builder/struct";
import formBuilder from "@/components/form-builder/index.vue";
import { useMessage } from "naive-ui";
import { useI18n } from "vue-i18n";
const formBuilderRef = ref();
const emits = defineEmits(["submit"]);
const { locale } = useI18n();
const dialogTitle = ref("");
const props = defineProps({
  schema: {
    type: Object as PropType<any>,
    required: true,
  },
});
const message = useMessage();
const visible = ref(false);
const open = ({ title, data }) => {
  visible.value = true;
  if (title) {
    dialogTitle.value = title;
  }
  if (data) {
    setTimeout(() => {
      console.log(formBuilderRef.value);
      const cloneData = JSON.parse(JSON.stringify(data));
      formBuilderRef.value.setForm(cloneData);
    });
  }
};
const close = () => {
  dialogTitle.value = "";
  visible.value = false;
};
const handleSubmit = () => {
  formBuilderRef.value
    .subimt()
    .then((res) => {
      if (res) {
        console.log(res);
        emits("submit", {
          title: dialogTitle.value || props.schema.title,
          data: res,
        });
        close();
      }
    })
    .catch((e) => {
      console.log(e);
    });
};
defineExpose({ open, close });
</script>

<style lang="scss" scoped></style>
